import pandas as pd

# 小组赛分组情况
group_file_path = "C://Users//54114//OneDrive//Desktop//FIFAPrediction//KeyCode//2022_world_cup_groups.csv"
groups_df = pd.read_csv(group_file_path)
group_A = ['Qatar', 'Ecuador', 'Senegal', 'Netherlands']
group_B = ['England', 'Iran', 'United States', 'Wales']
group_C = ['Argentina', 'Saudi Arabia', 'Mexico', 'Poland']
group_D = ['France', 'Australia', 'Denmark', 'Tunisia']
group_E = ['Spain', 'Costa Rica', 'Germany', 'Japan']
group_F = ['Belgium', 'Canada', 'Morocco', 'Croatia']
group_G = ['Brazil', 'Serbia', 'Switzerland', 'Cameroon']
group_H = ['Portugal', 'Ghana', 'Uruguay', 'South Korea']

# 世界杯比赛记录
world_cup_file_path = "C://Users//54114//OneDrive//Desktop//FIFAPrediction//KeyCode//world_cup_matches.csv"
HistoryWorldCupMatch = pd.read_csv(world_cup_file_path)

# 国际比赛记录(非世界杯)
international_match_file_path = ("C://Users//54114//OneDrive//Desktop//FIFAPrediction//KeyCode//international_matches"
                                 ".csv")
InternationalMatch = pd.read_csv(international_match_file_path)


# 32强历史战绩分析
def HistoryPerformance(group, im, wcm):
    # 初始化列表
    df = pd.DataFrame()

    # 遍历每个小组A~H 八个小组
    for country in group:

        # 该国家参加的国际比赛数量(非世界杯)
        games_im = len(im[(im['WinningTeam'] == country) | (im['LosingTeam'] == country)])

        # 没有足球国家队的国家
        if games_im == 0:
            wins_im = 0
            losses_im = 0
            winrate_im = 0

        # 普通国际比赛重要数据(胜、负、胜率)
        else:
            wins_im = len(im[im['WinningTeam'] == country])
            losses_im = len(im[im['LosingTeam'] == country])
            winrate_im = round(wins_im / games_im, 4)

        # 对世界杯比赛的统计(同上)
        games_wcm = len(wcm[(wcm['WinningTeam'] == country)
                            | (wcm['LosingTeam'] == country)])
        if games_wcm == 0:
            wins_wcm = 0
            losses_wcm = 0
            winrate_wcm = 0
        else:
            wins_wcm = len(wcm[wcm.WinningTeam == country])
            losses_wcm = len(wcm[wcm.LosingTeam == country])
            winrate_wcm = round(wins_wcm / games_wcm, 4)

        # Store all the inputs in a list
        match_situation = [country,
                           wins_im, losses_im, games_im, winrate_im,
                           wins_wcm, losses_wcm, games_wcm, winrate_wcm]

        # Append/add the list to the DataFrame
        df = df._append(pd.DataFrame([match_situation],
                                     columns=['country',
                                              'wins_im', 'losses_im', 'games_im', 'winrate_im',
                                              'wins_wcm', 'losses_wcm', 'games_wcm', 'winrate_wcm'],
                                     ))

    # 先按队伍世界杯历史战绩胜率排序(不是最终排位)
    return df.sort_values(by='winrate_wcm', ascending=False)


# 合并关键数据到小组赛分组情况上
grouped_teams = groups_df.groupby('Group')['Team'].apply(list).reset_index()
all_groups_performance = pd.DataFrame()

for index, row in grouped_teams.iterrows():
    group_performance = HistoryPerformance(row['Team'], InternationalMatch, HistoryWorldCupMatch)
    all_groups_performance = pd.concat([all_groups_performance, group_performance], ignore_index=True)

merged_df = pd.merge(groups_df, all_groups_performance, left_on='Team', right_on='country', how='left')
# 意义相同的两列删除一列
merged_df.drop('country', axis=1, inplace=True)
group_match_analysis_file_path = (
    "C://Users//54114//OneDrive//Desktop//FIFAPrediction//KeyCode//group_match_analysis.csv")
merged_df.to_csv(group_match_analysis_file_path, index=False)

# 数据集来源: Kaggle
# https://www.kaggle.com/abecklas/fifa-world-cup
